vcMotionController

Motion controller is a behavior that is used to control motion of a mechanism through associated vcLinkJoints.

See in: Overview

Module: vcRobotics2

Parent: vcBehavior

Children -

Referenced by: vcControllerGroup.Controllers, vcJointDriver.ActiveController, vcJointDriver.OwnerController, vcSimJointDriverExportField.Controller, ... (see more)
vcControllerGroup.Controllers
vcJointDriver.ActiveController
vcJointDriver.OwnerController
vcSimJointDriverExportField.Controller
vcSingleDofLinkJoint.Controller

Properties

Learn how to use properties here. The properties are also inherited from the parent class.

NameTypeAccessDescription
DriverCountIntegerRGets the number of internal drivers.
DriverPositionslist[Real]RWGets or sets a list of internal driver positions.
DriversvcList[vcJointDriver]RGets all internal drivers in their indexed order.
ExternalDriverCountIntegerRGets the number of external drivers.
ExternalDriverPositionslist[tuple[Integer, Real]]RWGets or sets a list of external driver positions. Each item is a tuple of (int driverIndex, double driverValue).
ExternalDriversvcList[vcJointDriver]RGets a list of external drivers in the order they appear in their indexed list. Empty slots are skipped.
GroupsvcList[vcControllerGroup]RGets all controller groups created on this controller.
IsStoppedBooleanRGets the current stopped state.
KinematicsvcKinematicsRWGets or sets the vcKinematics object to use with this controller.

Methods

Learn how to use methods here. The methods are also inherited from the parent class.

NameReturn TypeParametersDescription
abortNoneNoneStops all movement (immediate) and clears the target / motion queue.

Parameters:
None

Returns:
None
addCoordinatedTargetIntegervcMotionControllerTarget targetAdds the given target to an internal queue.
See more
You can construct a target in Python with vcPtpTarget(), vcLinearTarget() or vcMultiDriverTarget().

Call moveCoordinated() after adding one or more targets to make sure motions are being processed.

If target.TargetId is a positive integer, it is taken to mean an expected targetId value. This id value must not already be in use.
If target.TargetId is zero, the next free id is automatically assigned to this target, and returned from this method call.

Parameters:
targetId (int): Identification number for the target.
driverIndex (int): Index of the driver that this target applies to.
isExternal (bool): False if this target applies to an internal driver, True if it applies to an external driver.
valueType (vcDriverTargetValueType): Determines what the 'value' parameters means.
value (float): The target value. Also see valueType.
isSynchronized (bool): If True, this target will be marked to be synchronized with other targets for which this parameter is True.
maxVelocity (float): Maximum velocity used for planning the motion. If not provided, setting in the vcJointDriver will be used.
maxAcceleration (float): Maximum acceleration used for planning the motion. If not provided, setting in the vcJointDriver will be used.
maxDeceleration (float): Maximum deceleration used for planning the motion. If not provided, setting in the vcJointDriver will be used. The value must be positive.
maxJerk (float): Maximum jerk used for planning the motion. If not provided, setting in the vcJointDriver will be used.

Returns:
int: targetId assigned to the target. If the given targetId was positive, this will always be the same value.

Exceptions:
ValueError: When targetId is a negative value.
addIndependentTargetIntegerInteger targetId,
Integer driverIndex,
Boolean isExternal,
vcDriverTargetValueType valueType,
Real value,
Boolean isSynchronized,
Optional Keyword[maxVelocity = Real],
Optional Keyword[maxAcceleration = Real],
Optional Keyword[maxDeceleration = Real],
Optional Keyword[maxJerk = Real]
Call to add an independent motion target for a specific internal or external driver into an internal buffer.
Call moveIndependent() to plan and clear all targets from this buffer.

A target can have a target value for either position or velocity, selected with the valueType parameter.

It is possible to synchronize the durations of motions resulting from selected targets. The value of "isSynchronized" will determine whether
See more
this target is included in the list of motions to synchronize - other motions will remain time optimal. The synchronization is only performed
when planning the motions and is not updated subsequently if, e.g., a new un-synchronized target is given to one of the involved drivers
before the motions have been completed.

If target.TargetId is a positive integer, it is taken to mean an expected targetId value. This id value must not already be in use unless
it was used for this same driver.
If target.TargetId is zero, the next free id is automatically assigned to this target, and returned from this method call.

An independent motion can replace a previous independent motion for the same driver. targetId does not have to be the same as that of the
previous motion but it can be.
The previous motion will be cancelled, i.e., TargetStatusChanged with 'Cancelled' eventType will be raised.

Parameters:
targetId (int): Identification number for the target.
driverIndex (int): Index of the driver that this target applies to.
isExternal (bool): False if this target applies to an internal driver, True if it applies to an external driver.
valueType (vcDriverTargetValueType): Determines what the 'value' parameters means.
value (float): The target value. Also see valueType.
isSynchronized (bool): If True, this target will be marked to be synchronized with other targets for which this parameter is True.
maxVelocity (float): Maximum velocity used for planning the motion. If not provided, setting in the vcJointDriver will be used.
maxAcceleration (float): Maximum acceleration used for planning the motion. If not provided, setting in the vcJointDriver will be used.
maxDeceleration (float): Maximum deceleration used for planning the motion. If not provided, setting in the vcJointDriver will be used. The value must be positive.
maxJerk (float): Maximum jerk used for planning the motion. If not provided, setting in the vcJointDriver will be used.

Returns:
(int): targetId assigned to the target. If the given targetId was positive, this will always be the same value.

Exceptions:
ValueError: When targetId is a negative value.
checkDriverValueLimitsBooleanNoneVerifies that all internal and external vcJointDrivers in this vcMotionController
See more
fall within their current min and max (position) value limits.
If this is true, or there are no such drivers, it returns true. Otherwise, returns false.

Returns:
bool: True if all drivers fall within their limits, False otherwise.
clearTargetsNoneNoneIf there are any queued vcMotionControllerTargets, clears them for the queue.
createDrivervcJointDriverString nameCreates a new driver and adds it to this controller's internal drivers collection.
See more
Parameters:
name (str): A name for the driver. Must be unique among all internal drivers in this controller.

Returns:
vcJointDriver: The newly created driver.

Exceptions:
ValueError: When given name is empty or a driver with the same name already exists.
RuntimeError: when driver can't be created e.g. due to connected export interface.
createGroupvcControllerGroupOptional Keyword[name = String]Creates a group into this controller, then returns a reference to the created group.
See more
The name is set if given, otherwise a free name will be assigned.

Parameters:
name (str): An optional name to set for the new group.

Returns:
vcControllerGroup: The created group.
deleteGroupNoneString groupNameDeletes the group from this controller. Also see vcControllerGroup.delete().
See more
Parameters:
groupName (str): The name of the group to delete.

Exceptions:
ValueError: When a group with the given name cannot be found.
excludeDriverFromCoordinatedMotionsBooleanInteger driverIndexExcludes an internal driver from coordinated motions so that it can be controlled with independent motions instead.
See more
The driver can only be excluded while the simulation is running and there is no ongoing coordinated motion
that already uses the driver. The exclusion is cleared automatically when simulation resets.

Parameters:
driverIndex (int): Index of the internal driver to exclude.

Exceptions:
RuntimeError: When trying to enable this functionality when the simulation is not running.

Returns:
bool: True if the driver is now (or was already) excluded, otherwise false.
getNearestValueslist[Real]List[Real] targetValues,
List[Real] referenceValues,
Boolean respectLimits
A helper method for adjusting full driver rotations so that the end results are as close to the given reference values as possible.
See more
This will only ever apply +/- 360 degrees steps, even if vcJointDriver.TurnSpan has another value.
If vcJointDriver.TurnSpan is zero, this method has no effect on that driver.

Parameters:
targetValues (list[float]): The desired values in any revolution. For example, results of vcKinSolver.inverse().
referenceValues (list[float]): Reference values guide turn selection. For example, last known internal driver values.
respectLimits (bool): If True, solution outside driver limits are not accepted.

Exceptions:
RuntimeError: When respectLimits was true and the method couldn't converge on good values.

Returns:
list[float]: Nearest values.
moveCoordinatedBooleanNoneThis method should be called after adding one or more coordinated targets (see addCoordinatedTarget). This will make sure that motion execution is
See more
ongoing and will trigger motion planning if the next coordinated target can be started immediately. If motion is already ongoing and cannot be
interrupted at this time, planning the next motion will happen when the current motion finishes or enters its blending zone.

This method is non-blocking. If you want to know when the motion completes, start awaiting for the OnTargetStatusChanged event
before calling this method.

Returns:
bool: True on success, false on error.
moveIndependentIntegerNoneThis call plans and starts all independent motions added since the last call to this method. Also see addIndependentTarget.
See more
This method is non-blocking. If you want to know when the motion completes, start awaiting for the OnTargetStatusChanged event
before calling this method.

Returns:
int: Number of planned targets on success.

Exceptions:
ValueError: When motion planning failed.
resumeNoneNoneResumes motion if it was stopped.

Parameters:
None

Returns:
None
returnDriverToCoordinatedMotionsBooleanInteger driverIndex,
Optional Keyword[resetTargetValue = Real],
Optional Keyword[valuePickingStrategy = vcClosestValuePickingStrategy]
Returns a previously excluded internal driver back to coordinated motions.

The driver cannot be returned if there is an ongoing coordinated motion that would immediately take control of it.
See more
It will be automatically disabled when the simulation resets.

The optional parameters allow one to reset the driver's turns with the same call. See vcJointDriver.resetTurns.

Parameters:
driverIndex (int): Index of the internal driver to return.
Optional: resetTargetValue (float | None): Target for Value. Default value is None, meaning no turn reset is done.
Optional: resetValuePickingStrategy (vcClosestValuePickingStrategy): Strategy for picking the closest value. vcClosestValuePickingStrategy.CLOSEST is used by default.

Exceptions:
ValueError: When the given driverIndex is out of bounds.

Returns:
bool: True if the driver is now (or was already) participating in coordinated motions, otherwise false.
setToolCenterPointtuple[Boolean, list[vcJointDriver]]vcMatrix newPosition,
vcMotionCoordinateSystem coordinateSystem,
Boolean pickNearestTurns,
Boolean respectLimits,
vcRobotConfiguration desiredConfiguration
An advanced setter for current tool center point position.
See more
Parameters:
newPosition (vcMatrix): The position to set.
coordinateSystem (vcMotionCoordinateSystem): The coordinate system to use when setting the position.
pickNearestTurns (bool): If True, turn handling is invoked.
respectLimits (bool): If True, driver limits are respected.
desiredConfiguration (vcMotionConfiguration): The desired configuration to attain when setting the position.

Exceptions:
RuntimeError: When respectLimits was true and the method couldn't converge on good values.

Returns:
(bool, list[vcJointDriver]): A boolean True if the position was reachable and a list of drivers that went out of limits, if any.
stopBooleanNoneStops all movement (immediate) without clearing the target / motion queue.
See more
Resume motion by calling resume(), moveIndependent() or moveCoordinated().

Parameters:
None

Returns:
bool: True on success.
testExternalDriverValueLimitslist[vcJointDriver]List[tuple[Integer, Real]] valuesTests which external drivers would be outside their (position) value limits if the given values were applied to them.
See more
This method doesn't assign the values to the drivers, it only tests them.

Parameters:
values (list[tuple(int, float)]): Applies the given values based on index value 2-tuples.

Returns:
list[vcJointDriver]: List of drivers outside of limits.

Exceptions:
IndexError: When values contain one or more invalid index.
testInternalDriverValueLimitslist[vcJointDriver]List[Real] valuesTests which internal drivers would be outside their (position) value limits if the given values were applied to them.
See more
This method doesn't assign the values to the drivers, it only tests them.

Parameters:
values (list[float]): Applies the given values starting from index 0.

Returns:
list[vcJointDriver]: List of drivers outside of limits.

Exceptions:
IndexError: When values has excessive number of values.
testInternalDriverValueLimitslist[vcJointDriver]List[tuple[Integer, Real]] valuesTests which internal drivers would be outside their (position) value limits if the given values were applied to them.
See more
This method doesn't assign the values to the drivers, it only tests them.

Parameters:
values (list[tuple(int, float)]): Applies the given values based on index value 2-tuples.

Returns:
list[vcJointDriver]: List of drivers outside of limits.

Exceptions:
IndexError: When values contain one or more invalid index.
waitUntilTargetsReachedobjectOptional[List[Integer] targetIds],
Optional Keyword[timeout = Real]
Blocks script execution until given targets are reached.

This function returns an awaitable task. It must be awaited.
See more
If no targetIds are specified, the awaitable is done when the next motion has fully completed, i.e.,
a target has been reached exactly.

If one or more targetIds are specified, the awaitable is done when all of those motions have finished
or failed, or have been cancelled.

Parameters:
targetIds list[int]: An optional list of target ids of the motions to monitor.
timeout [float]: An optional time out value, in seconds.

Returns:
Awaitable[Tuple]: The task instance. When awaited returns a list of tuples, where the tuples are received OnStatusChanged event arguments,
in the order they were raised in.

Events

Learn how to use events here. The events are also inherited from the parent class.

NameParametersDescription
OnGroupAddedvcControllerGroup groupTriggered when a new controller group is created in this controller.

Parameters:
group (vcRobotics2.vcControllerGroup): new group.
OnGroupRemovedNoneTriggered when a controller group has been deleted from this controller.
OnPositionUpdatedvcMotionController controllerTriggered when controller updated the robot's state e.g. driver positions

Parameters:
controller (vcMotionController): Sender.
OnTargetStatusChangedvcMotionController controller,
vcTargetStatusChangedEventType eventType,
int targetId
Triggered when a notable event happens in a programmed motion, e.g. the motion has been finished.
See more
Parameters:
controller (vcMotionController): Sender.
eventType (vcTargetStatusChangedEventType): Defines what kind of event happened.
targetId (int): Matches the targetId value of the vcMotionTarget that was used to plan this motion.

Example: Move Joints

"""Example of coordinated multi-joint motion using the MotionController behavior."""

import vcCore as vc
import vcRobotics2 as vc_robo2

comp = vc.getComponent()
mc = comp.findBehavior("MotionController")

async def move(joint_targets: list[float], motion_time = None):
  if len(joint_targets) > mc.DriverCount:
    print("More joint targets given than drivers exist")
    return
  target = vc_robo2.vcMultiDriverTarget()
  target.InternalDriverValues = list(enumerate(joint_targets)) # list of tuples with index
  if motion_time:
    target.MotionTime = motion_time
  mc.addCoordinatedTarget(target)
  mc.moveCoordinated()
  await mc.waitUntilTargetsReached()

async def OnRun():
  """Use 'async' for defining time-consuming functions. Use 'await' for time-consuming method and function calls."""
  while True:
    await move([200.0, 400.0, 300.0], 1.0) # With motion time parameter
    await move([-200.0, -400.0, 100.0])
    await move([0.0, 0.0, 0.0])

Example: Move Driver

"""Example of blocking and non-blocking driver motion using the MotionController behavior."""

import vcCore as vc
import vcRobotics2 as vc_robo2

comp = vc.getComponent()
mc = comp.findBehavior("MotionController")

POSITION_TARGET = vc_robo2.vcDriverTargetValueType.POSITION
TARGET_ID = 0

def move_driver_nonblocking(driver_index: int, target: float):
  """Starts the motion to given target and does not wait for motion to complete. Can be called from outside OnRun. Good for e.g. controlling gripper fingers."""
  mc.addIndependentTarget(TARGET_ID, driver_index, False, POSITION_TARGET, target, False)
  mc.moveIndependent()

async def move_driver(driver_index: int, target: float):
  """Moves to given target and waits for motion to complete."""
  mc.addIndependentTarget(TARGET_ID, driver_index, False, POSITION_TARGET, target, False)
  mc.moveIndependent()
  await mc.waitUntilTargetsReached()

async def OnRun():
  """Use 'async' for defining time-consuming functions. Use 'await' for time-consuming method and function calls."""
  while True:
    # Blocking function calls
    await move_driver(0, 500.0)
    await move_driver(0, 0.0)
    # Non-blocking function calls
    move_driver_nonblocking(0, 500.0)
    await vc.delay(1.0)
    move_driver_nonblocking(0, 0.0)
    await vc.delay(1.0)

Example: Motion Controller Example

"""
Controller has two joints.
Create two targets and make both joints move simultaneously back and forth with coordinates motions."""

import vcCore as vc
import vcBehaviors as vc_beh
import vcRobotics2 as vc_robo2

comp = vc.getComponent()
mc = comp.findBehavior('MotionController')
app = vc.getApplication()
world = vc.getWorld()

async def OnRun():
  target1 = vc_robo2.vcMultiDriverTarget()
  target1.InternalDriverValues = [(0, 200), (1, 500)]
  target1.TargetId = 1
  target2 = vc_robo2.vcMultiDriverTarget()
  target2.InternalDriverValues = [(0, 0), (1, 0)]
  target2.TargetId = 2

  while True:
    mc.clearTargets()
    mc.addCoordinatedTarget(target1)
    mc.addCoordinatedTarget(target2)
    mc.moveCoordinated()
    await mc.waitUntilTargetsReached([target2.TargetId])  # Wait until last target is reached